package net.jielan188.hd.vo.common;

import net.jielan188.hd.bean.user.User;
import net.jielan188.hd.service.user.UserServiceT;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.Map;
import java.util.Set;

/**
 * 权限管理
 * Created by hgg on 2017-01-24.
 */
public class ShiroRealm extends AuthorizingRealm implements Serializable{

    @Autowired
    private UserServiceT userService;

    public static Map<String,Object> roleMap = new HashedMap();

    /**
     * 为当前登录成功的用户授予角色和权限
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals ) {

        String userName = (String)principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        try {

            //权限缓存 存放在内存中
            Set<String> menuSet = (Set<String>)roleMap.get( userName + "currentUserMenuList" );
            if( menuSet == null ){
                roleMap.put( userName + "currentUserMenuList",userService.getPermissionByUserName( userName ) );
            }
            authorizationInfo.setStringPermissions( (Set<String>)roleMap.get( userName + "currentUserMenuList" ) );
            return authorizationInfo;
        } catch ( Exception e ) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 验证当前登录的用户
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token ) throws AuthenticationException {

        try {

            String userName = (String)token.getPrincipal();
            User resultUser = userService.getUserByUserName( userName );

            if( resultUser != null ){

                AuthenticationInfo authcInfo = new SimpleAuthenticationInfo( resultUser.getUserName(),resultUser.getUserPass(),"xx");
                //权限缓存 存放在内存中
                roleMap.put( userName + "currentUserMenuList",userService.getPermissionByUserName( userName ) );
                return authcInfo;
            }
        } catch ( Exception e ) {
            e.printStackTrace();
        }

        return null;
    }
}
